﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using ForfiterStockInfo.Entities;
using System.Xml;
using System.IO;
using System.Globalization;
using HtmlAgilityPack;

namespace ForfiterStockInfo.Client
{
    public static class BankierParser
    {
        private const string tableOpenTag = "<table uxe border=\"0\" cellpadding=\"3\" cellspacing=\"1\" style=\"text-align: right\" width=\"99%\" bgcolor=\"#D1D1D1\">";
        private const string tableEndTag = "</table>";

        public static Collection<Record> GetRecords(string pageSource)
        {
            var result = new Collection<Record>();

            if (pageSource == null || pageSource == string.Empty)
                return result;

            int tableOpenPos = pageSource.IndexOf(tableOpenTag);
            string fromTableOpen = pageSource.Remove(0, tableOpenPos);
            int tableClosePos = fromTableOpen.IndexOf(tableEndTag);
            string table = fromTableOpen.Remove(tableClosePos + tableEndTag.Length);

            HtmlDocument document = new HtmlDocument();
            document.LoadHtml(table);
            string innerText = document.DocumentNode.InnerText;
            innerText = innerText.Replace("&nbsp;", string.Empty);
            var lines = innerText.Split('\n');

            var numberFormatProvider = new NumberFormatInfo();
            numberFormatProvider.NumberDecimalSeparator = ".";
            numberFormatProvider.NumberGroupSizes = new int[]{3};

            var dateTimeFormatProvider = new DateTimeFormatInfo();
            dateTimeFormatProvider.SetAllDateTimePatterns(new string[] { "MM-ddhh:mm" }, 'Y');

            for (int i = 0; i < (lines.Count() - 59) / 13; i++)
            {
                int offset = 59 + 13 * i;
                var record = new Record();
                record.Stock = new Stock();
                record.Stock.FullName = lines[offset];
                record.Stock.Name = lines[offset + 1];
                record.Price = Convert.ToDecimal(lines[offset + 2], numberFormatProvider);
                record.ChangePrice = Convert.ToDecimal(lines[offset + 3], numberFormatProvider);
                var changePercent = lines[offset + 4];
                record.ChangePercent = Convert.ToDecimal(changePercent.Remove(changePercent.Length - 1), numberFormatProvider);
                record.Volume = Convert.ToInt32(lines[offset + 5]);
                record.Turnover = Convert.ToInt32(lines[offset + 6]);
                record.OpeningPrice = Convert.ToDecimal(lines[offset + 7], numberFormatProvider);
                record.MaxPrice = Convert.ToDecimal(lines[offset + 8], numberFormatProvider);
                record.MinPrice = Convert.ToDecimal(lines[offset + 9], numberFormatProvider);

                result.Add(record);
            }

            return result;
        }
    }
}
